<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.css" rel="stylesheet">
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/nprogress/0.2.0/nprogress.js"></script>

</head>

<body>
    <h1>拦截器练习</h1>
    <input type="text" id="ipt">
    <button id="btn">提交</button>
    <script>
        // 创建asxis实例
        const myAxios = axios.create({
      baseURL: "/",
      timeout: 10000,
      headers: {}
    })
  // 添加请求拦截器
  myAxios.interceptors.request.use((config)=>{
        //1.获取token,并让请求头携带token
        const token= 'wjsfgafdsjgfhff.dsfsdagsgegdfgsd.dsaggasfgdfafdg'
        config.headers.token=token;
    //2.让进度条开始 (直接调用)
    NProgress.start();
    // 放行
    return config;
  },(error)=>{
    return Promise.reject(error)
  })
    // 添加响应拦截器
    myAxios.interceptors.response.use((response)=>{
    //1.让进度条结束
    NProgress.done();
    //2.对请求到的结果进行处理,只拿正确的信息,如果错误的信息,直接交给异常处理
    if(response.data.code!==10000){
       return Promise.reject(response.data.msg)
    }
    return response.data.data
    },(error)=>{
        return Promise.reject(error)
    })
    const oIpt = document.getElementById('ipt')
    const oBtn = document.getElementById('btn');
    oBtn.onclick= async function(){
        const iptValve = oIpt.value;
        try{
            const re = await myAxios.get('/user',{
                params:{
                    userId:iptValve
                }
            })
            console.log(re);
        }catch(e){
            console.log(e, 'you is sb');
        }
    }

    </script> 
</body>

</html>